package cn.hjh.Service;

import cn.hjh.dao.UserDaoFactory;
import cn.hjh.dao.user.UserDao;
import cn.hjh.dao.user.UserDaoImpl;
import cn.hjh.dao.user.UserMapper;
import cn.hjh.entity.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import util.MybatisUtil;

import javax.annotation.Resource;

/**
 * 用户业务类
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    //使用log4j日志记录器
    private static final Logger log = Logger.getLogger(UserServiceImpl.class);

    /*//实例化所依赖的UserDao对象
    private UserDao dao = new UserDaoImpl();*/

    //通过工厂获取所依赖的用户DAO对象
    //private UserDao dao = UserDaoFactory.getInstance();
    public void addNewUser(User user) {
        //调用UserDao的方法保存用户信息
        dao.save(user);
    }

    public void setDao(UserDao dao) {
        this.dao = dao;
    }

    /*@Resource*/
    public UserServiceImpl(UserDao dao){
        this.dao = dao;
    }

    @Autowired
    @Qualifier("userDao")
    //为dao属性注入名为userDao的Bean
    /*@Resource(name = "userDao")*/



    //private User userDao;

    //第6章示例1
    private UserDao dao;

    //无参构造方法
    public UserServiceImpl(){}

    public boolean addNewUser1(User user){
        log.info("添加用户" + user.getUserName());
        SqlSession sqlSession = null;
        boolean flag = false;
        try {
            sqlSession = MybatisUtil.createSqlSession();
            if (sqlSession.getMapper(UserMapper.class).add(user) > 0)
                flag = true;
            sqlSession.commit();
            log.info("成功添加用户" + user.getUserName());
        }catch (Exception e){
            log.error("添加用户" + user.getUserName() + "失败",e);
            sqlSession.rollback();
            flag = false;
        }finally {
            MybatisUtil.closeSqlSession(sqlSession);
        }
        return  flag;
    }


}
